const express = require("express");
const port = 9000;
const app = express();
const url = require('url');
const path = require('path');
const fs = require('fs').promises;
const libre = require('libreoffice-convert');
libre.convertAsync = require('util').promisify(libre.convert);
const multer = require('multer');
const os = require('os');
//获取本机ip 
function getIPAdress() {
    var interfaces = os.networkInterfaces();
    //console.log('interfaces',interfaces);
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }
}
const host = getIPAdress();

console.log('ServerAddress',host);
const storage = multer.diskStorage({
  //设置上传后文件路径
  destination: function (req, file, cb) {
    cb(null, './uploads')
  },
  //给上传文件重命名
  filename: function (req, file, cb) {
    const fileFormat = (file.originalname).split(".");
    const fistname = fileFormat[0];
    const extname = fileFormat[1];
    const newfilename = fistname + '-' + Date.now() + "." + extname;
    cb(null, newfilename);
  }
});
//添加配置文件到muler对象。
const upload = multer({
  storage: storage
});

app.post('/api/convert-to-pdf', upload.single('docflie'), function (req, res, next) {
  // 文件属性
  console.log(req.file);
  const file = req.file, docname = file.originalname, name = file.filename, filename = docname.split('.')[0], type = file.mimetype, upfilepath = file.path;
  const ext = '.pdf';
  const pdfname = filename + ext;

  //Path where the converted pdf will be placed/uploaded
  const outputPath = path.join(__dirname, `./uploads/${filename}${ext}`);
  //异步转换
  convertTopdf(upfilepath);

  async function convertTopdf(filedir) {
    try {
      const docxBuf = await fs.readFile(filedir);
      console.log('Word File readding······');
      // Convert it to pdf format with undefined filter (see Libreoffice docs about filter) 
      let pdfBuf = await libre.convertAsync(docxBuf, ext, undefined);
      console.log('Word File Converting······');
      // Here in done you have pdf file which you can save or transfer in another stream 
      await fs.writeFile(outputPath, pdfBuf);
      console.log('Word File Converted.');
      // 将本地路径转换为文件URL
      const download_url = url.format({
        protocol: 'http',
        hostname: host,
        port: port,
        pathname: path.posix.join('/uploads',pdfname)
      });
 
      res.json({ "result": "success", "msg": "文档转换成功！", "download_url": download_url });
      console.log(pdfname+"Convert successfull");


      //Delete the files from directory after the use 

      fs.rm(filedir)
      //file removed
      console.log('Word File deleted.');
      //一分钟后删除完成的文件
      delayedDelete(outputPath,60000);
      console.log('PDF File will be deleted after 1min');

    } catch (error) {
      console.error(error)
      fs.rm(filedir)
      console.log('Word File deleted.');

      res.json({ "result": "failed", "msg": "文档转换失败！", "download_url": null });
    }

  }
});
 // 延时删除文件单位为毫秒
async function delayedDelete(filePath, delay) {
  setTimeout(async () => {
    try {
      await fs.unlink(filePath);
      console.log(`文件 ${filePath} 已被删除。`);
    } catch (error) {
      console.error(`无法删除文件 ${filePath}: ${error}`);
    }
  }, delay);
}

//暴露静态目录
app.use('/uploads', express.static('uploads'));

app.listen(port, () =>
  console.log(
    `转换服务已启动浏览器打开 http://${host}:${port}`,
  ),
);